package com.ruoyi.framework.excel;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.merge.AbstractMergeStrategy;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.List;

/**
 * 合并策略
 *
 * @author dyun
 */
public class ExcelMergeStrategy extends AbstractMergeStrategy {
    private final ExcelMerge excelMerges;

    public ExcelMergeStrategy(ExcelMerge excelMerges) {
        this.excelMerges = excelMerges;
    }

    @Override
    protected void merge(Sheet sheet, Cell cell, Head head, Integer integer) {
        //需要合并的列
        List<Integer> columns = excelMerges.getColumns();
        //从第几行开始填充
        int startRow = excelMerges.getStartRow();
        //需要合并的行数
        List<Integer> mergeRows = excelMerges.getMergeRows();
        if (cell.getRowIndex() == startRow && cell.getColumnIndex() == 0) {
            //有几行需要合并
            int endRow;
            for (Integer num : mergeRows) {
                if (num > 1) {
                    endRow = startRow + num - 1;
                    for (int c : columns) {
                        sheet.addMergedRegionUnsafe(new CellRangeAddress(startRow,
                                endRow, c, c));
                    }
                    startRow = endRow;
                }
                startRow++;
            }
        }
    }
}